package com.gs.netty.support.resolver;

import com.alibaba.fastjson2.JSON;


import com.gs.netty.core.SerializableEnum;
import com.gs.netty.core.annotation.CommandMapping;
import com.gs.netty.core.annotation.RequestPayload;
import com.gs.netty.core.resolver.args.HandlerMethodArgumentResolver;
import com.gs.netty.websocket.remoting.req.Request;
import io.netty.util.CharsetUtil;
import org.springframework.core.MethodParameter;

/**
 * @RequestBody 注解参数解析器
 */
public class RequestBodyJsonMethodProcessor implements HandlerMethodArgumentResolver<Request> {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        CommandMapping methodAnnotation = parameter.getMethodAnnotation(CommandMapping.class);
        if (methodAnnotation == null) {
            return false;
        }
        SerializableEnum serializable = methodAnnotation.serializable();
        return SerializableEnum.JSON.equals(serializable) && parameter.hasParameterAnnotation(RequestPayload.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, Request request) throws Exception {
        Class<?> targetClass = parameter.getParameterType();
        String data = request.getPayload();

        if (data == null) {
            return null;
        }

        if (targetClass.isAssignableFrom(String.class)) {
            return data;
        }

        if (targetClass.isAssignableFrom(data.getClass())) {
            return data;
        }
        
        return JSON.parseObject(data, targetClass);
    }
}
